//
//  HD_LY_DownloadManager.m
//  HDShenYangIndustrialMuseum
//
//  Created by liuyi on 2017/3/11.
//  Copyright © 2017年 hengdawb. All rights reserved.
//

#import "HD_LY_DownloadManager.h"
#import "MBProgressHUD.h"
#import "ZipArchive.h"

#import "HDDeclare.h"

//下载IP地址
#define IP_Header   @"http://61.161.217.174:65529/LiaoNingSmartGuide_Res/"//外网IP
#define IP_Local    @"http://192.168.10.155:12345/LiaoNingSmartGuide_Res/"//内网IP

//资源文件名
#define MainFileName   @"HDCLMY_Res"
#define DB_FileName    @"DB"
#define Map_FileName   @"map"




@interface HD_LY_DownloadManager ()<MBProgressHUDDelegate>

@property (strong, nonatomic) NSString *urlString;//当前下载的url
@property (strong, nonatomic) NSString *fileNo;//单包下载的展品编号
@property (strong, nonatomic) NSString *declareLan;//当前下载的语种
@property (strong, nonatomic) MBProgressHUD *hud;//下载进度弹窗

@end

/*
 使用说明：
 不同项目需更换的地方：
 1、IP_Header（IP_Local）和后面拼接的urlStr
 eg:http://47.93.81.30/HD_down/HD-KLMY-RES/%@/%@.zip
 2、解压文件名路径:directoryPath
 eg:.../Caches/HDCLMY_Res/CHINESE/map
 */


static HDDeclare *declare;


@implementation HD_LY_DownloadManager

- (instancetype)init
{
    self = [super init];
    if (self) {
        declare = [HDDeclare sharedDeclare];
    }
    return self;
}
/*
 数据库：base.zip
 地图：map.zip
 整包：CHINESE/CHINESE.zip
 单包：CHINESE/0001.zip
 */

#pragma mark ----
- (void)myDownloadAction:(UIViewController *)VC withType:(Download_Type)type WithFileNo:(NSString *)fileNo;
{
    HDDeclare *declare = [HDDeclare sharedDeclare];
    _declareLan = declare.language.uppercaseString;//可设置为：declare.language
    _myDownloadType = type;
    _downloadingVC = VC;
    _fileNo = fileNo;
    //下载地址
    NSString  *urlStr;
    if (type == kDownload_Tpye_Sqlite) {
        //下载数据库
        urlStr = @"base.zip";
    }else if (type == kDownload_Tpye_AllRes)
    {
        //下载整包资源
        urlStr = [NSString stringWithFormat:@"%@.zip",_declareLan];
    }else if (type == kDownload_Tpye_OneRes)
    {
        //下载单包资源
        urlStr = [NSString stringWithFormat:@"%@/%@.zip",_declareLan,fileNo];
    }
    else if (type == kDownload_Tpye_MapRes)
    {
        //下载地图
        urlStr = [NSString stringWithFormat:@"%@.zip",@"map"];
    }
    NSString *filename = @"AllRes";//[urlStr stringByReplacingOccurrencesOfString:@"/" withString:@"_"];//设置下载zip的文件名
    //获得网络管理者
    NSString *url = @"http://47.93.81.30/HD_down/HuLuDao_Res/CHINESE.zip";//[NSString stringWithFormat:@"%@%@",[HDDeclare IP_Request_Header],urlStr];
#warning ----在这里判断是否是内网下载，更换IP地址
    /*
    if([_declare isWifiLAN])
    {
        url = [NSString stringWithFormat:@"%@%@/%@.zip",IP_Local,@"CHINESE",_declare.language];
        LOG(@"________内网下载：_______");
    }*/
    NSLog(@"________下载：%@_______",url);
    self.urlString = url;
    [self downloadRes:url fileName:filename];
}

- (void)downloadRes:(NSString *)url fileName:(NSString *)name
{
    _hud = [MBProgressHUD showHUDAddedTo:_downloadingVC.navigationController.view animated:YES];
    __block MBProgressHUD *progressHUD = _hud;
    _hud.mode = MBProgressHUDModeDeterminate;
    _hud.label.text = @"正在下载...";
    // Configure the button.
    [_hud.button setTitle:NSLocalizedString(@"取消", @"HUD cancel button title") forState:UIControlStateNormal];
    [_hud.button addTarget:self action:@selector(downloadCancle) forControlEvents:UIControlEventTouchUpInside];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //开启任务下载资源
        [[HSDownloadManager sharedInstance] download:url progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //NSLog(@"________%f_______receivedSize:%ld_______expectedSize:%ld",progress, receivedSize, expectedSize);
                CGFloat progressPercent = progress;
                progressHUD.progress = progressPercent;
                NSString *progressStr = [NSString stringWithFormat:@"%.1fM%@",(expectedSize-receivedSize)/1024/1024.0,@"正在下载"];
                _hud.label.text = NSLocalizedString(progressStr, @"HUD loading title");
            });
        } state:^(DownloadState state) {
            [self feedbackDownloadState:state];
            if (state == DownloadStateCompleted)
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [progressHUD hideAnimated:YES];
                    [self transformDataToZip:url resName:name];
                });
            }
            if (state == DownloadStateFailed) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [progressHUD hideAnimated:YES];
                    NSLog(@"__________下载失败_________");
                    [self showDownloadFailedTip];
                });
            }
        }];
    });
}

//为缓存文件添加.zip后缀,解压使用
- (void)transformDataToZip:(NSString *)url resName:(NSString *)name
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [_hud removeFromSuperview];
        MBProgressHUD *progress = [MBProgressHUD showHUDAddedTo:_downloadingVC.navigationController.view animated:YES];
        progress.label.text = NSLocalizedString(@"正在加载资源中...", @"HUD loading title");
        [progress showAnimated:YES];
        
        NSString *filePath = HSFileFullpath(url);//原始下载文件路径
        NSString *destinationPath = declare.catch_path;// [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        destinationPath = [destinationPath
                           stringByAppendingPathComponent:name];//目标zip文件路径
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
            [[NSFileManager defaultManager] removeItemAtPath:destinationPath error:nil];
        }
        //判断是否移动
        NSError *error;
        if ([fileManager moveItemAtPath:filePath toPath:destinationPath error:&error] != YES)
        {
            NSLog(@"Unable to move file: %@", [error localizedDescription]);
            [progress hideAnimated:NO];
        }else
        {
            //解压目标路径下的zip文件
            NSLog(@"destinationPath: %@",destinationPath);
            if ([fileManager fileExistsAtPath:destinationPath]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self unzipFileWithPath:destinationPath];
                    [progress hideAnimated:NO];
                });
            }
        }
    });
}

//解压文件到指定文件夹下
- (void)unzipFileWithPath:(NSString *)zipPath
{
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *progress = [MBProgressHUD showHUDAddedTo:_downloadingVC.navigationController.view animated:YES];
        self.myDownloadState = kDownloadStateCompleted;
        progress.label.text = NSLocalizedString(@"正在加载资源...", @"HUD loading title");
        //创建解压目标文件夹
        NSString *path;
        if (_myDownloadType == kDownload_Tpye_Sqlite) {
            path = [NSString stringWithFormat:@"%@",DB_FileName];
        }else if (_myDownloadType == kDownload_Tpye_AllRes)
        {
            path = _declareLan;
        }else if (_myDownloadType == kDownload_Tpye_OneRes)
        {
            path = [NSString stringWithFormat:@"%@",_declareLan];
        }else if (_myDownloadType == kDownload_Tpye_MapRes)
        {
            path = [NSString stringWithFormat:@"%@/%@",_declareLan,Map_FileName];;
        }
        NSString *directoryPath = [NSString stringWithFormat:@"%@",declare.catch_path];//解压后的文件路径
        if ([[NSFileManager defaultManager] fileExistsAtPath:zipPath])
        {
            [SSZipArchive unzipFileAtPath:zipPath toDestination:directoryPath progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
                
            } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
                if (succeeded) {
                    NSLog(@"0000--:%@",directoryPath);
                    [progress hideAnimated:YES];
                    self.successBlock();
                    [[NSFileManager defaultManager] removeItemAtPath:zipPath error:nil];
                }
            }];
        }
    });
}

#pragma mark ---- 获取当前下载状态 ------
- (void)feedbackDownloadState:(DownloadState)state
{
    switch (state) {
        case DownloadStateStart:
            self.myDownloadState = kDownloadStateStart;
            break;
        case DownloadStateSuspended:
            self.myDownloadState = kDownloadStateSuspended;
            break;
        case DownloadStateFailed:
            self.myDownloadState = kDownloadStateFailed;
            break;
        case DownloadStateCompleted:
            self.myDownloadState = kDownloadStateCompleted;
            break;
        default:
            break;
    }
}
#pragma mark  --- 下载失败提醒 -----
- (void)showDownloadFailedTip {
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:_downloadingVC.navigationController.view animated:YES];
        // Set the text mode to show only text.
        hud.mode = MBProgressHUDModeText;
        hud.label.text = NSLocalizedString(@"下载失败！请检查网络设置", @"HUD message title");
        // Move to bottm center.
        hud.offset = CGPointMake(0.f, 200);
        [hud hideAnimated:YES afterDelay:3.f];    });
}

#pragma mark ---cancle action-----
-(void)downloadCancle
{
    [[HSDownloadManager sharedInstance] cancle:self.urlString];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"download_cancle_noti" object:nil];
    [_hud hideAnimated:YES];
}

- (void)cancleDownload:(NSString *)url
{
    if (self.myDownloadState == kDownloadStateStart) {
        [[HSDownloadManager sharedInstance] cancle:url];
    }
}

- (void)cleanDownloder
{
    self.successBlock = nil;
}



@end




























